package com.heima.common.tess4j;

import lombok.Getter;
import lombok.Setter;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.awt.image.BufferedImage;

@Configuration
@ConfigurationProperties(prefix = "tess4j") // 自动红注入前缀为tess4j的属性
@Getter
@Setter
public class Tess4jClient {
    private String dataPath;
    private String language;


    /**
     * OCR图片文本识别
     * @param image 图片路径
     * @return 识别的文本内容
     * @throws TesseractException 识别失败
     */
    public String doOCR(BufferedImage image) throws TesseractException {
        // 1. 创建Tesseract对象
        ITesseract tesseract = new Tesseract();

        // 2. 设置字体库路径
        tesseract.setDatapath(dataPath);

        // 3. 设置语言
        tesseract.setLanguage(language);

        // 4. orc识别图片内容并替换回车和空格
        return tesseract.doOCR(image)
                .replaceAll("[\\r\\n]", "-")
                .replaceAll(" ", "");
    }
}
